﻿using AntMovement.Comm.Helper;
using AntMovement.Comm.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AntMovement.Comm
{
    /// <summary>
    /// 注册
    /// </summary>
    public class Enrollment : IChainedHandle
    {
        private Func<int, OutTimeModel> _query;
        public Func<int, OutTimeModel> Query => _query;
        private Func<int, bool, bool> _updateTime;
        public Func<int, bool, bool> UpdateTime => _updateTime;
        private volatile int _count = 0;
        public Enrollment(Func<int, OutTimeModel> query, Func<int, bool, bool> updateTime)
        {
            _query = query;
            _updateTime = updateTime;
        }

        public void Execute(byte[] request, List<byte> respond)
        {
            int count = Interlocked.Increment(ref _count);
            DateTime dateTime = DateTime.Now;
            respond.Add((byte)dateTime.Hour);
            respond.Add((byte)dateTime.Minute);
            respond.Add((byte)dateTime.Second);
            respond.Add((byte)count);
            int id = BytesHelper.BytesToInt((byte)dateTime.Hour, (byte)dateTime.Minute, (byte)dateTime.Second, (byte)count);
            respond.Add(3);
            respond.Add(0);
            respond.Add((byte)(UpdateTime.Invoke(id, false) ? 0 : 1));
            respond.Add(0);
            respond.Add(request[10]);
        }
    }
}
